package com.the_ring.chapter13;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.util.Base64;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.VideoDecoder;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.the_ring.chapter13.bean.ImagePart;
import com.the_ring.chapter13.work.CollectWork;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.UUID;

import io.netty.util.internal.SocketUtils;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void backWork() {
        // 1. 构建约束条件
        Constraints constraints = new Constraints.Builder()
                // .setRequiresBatteryNotLow(true)                 // 设备电量充足
                // .setRequiresCharging(true)                      // 设备正在充电
                .setRequiredNetworkType(NetworkType.CONNECTED)  // 已连接网络
                .build();

        // 2. 构建输入数据
        Data inputData = new Data.Builder()
                .putString("name", "小明")
                .putInt("height", 190)
                .putDouble("weight", 80)
                .build();

        // 3. 构建一次性工作请求
        String workTag = "OnceTag";
        OneTimeWorkRequest onceRequest = new OneTimeWorkRequest.Builder(CollectWork.class)
                .addTag(workTag)
                .setConstraints(constraints)
                .setInputData(inputData)
                .build();
        UUID workId = onceRequest.getId();

        // 4. 执行工作请求
        WorkManager workManager = WorkManager.getInstance(this);
        workManager.enqueue(onceRequest);   // 将工作请求加入到执行队列中

        // 获取指定编号的工作信息，并实时监听工作的处理结果
        workManager.getWorkInfoByIdLiveData(workId).observe(this, workInfo -> {
            if (workInfo.getState() == WorkInfo.State.SUCCEEDED) {
                Data outputData = workInfo.getOutputData();
                int resultCode = outputData.getInt("resultCode", 0);
                String resultDesc = outputData.getString("resultDesc");
                String desc = String.format("工作处理结果为：resultCode=%d, resultDesc=%s", resultCode, resultDesc);
            }
        });
    }

    /**
     * 获取指定时间点的请求参数
     * @param position
     * @return
     */
    private RequestOptions getOptions(int position) {
        // 指定某个时间点位置的帧，单位为 毫秒
        RequestOptions options = RequestOptions.frameOf(position * 1000 * 1000);
        // 获取最近的视频帧
        options.set(VideoDecoder.FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST);
        // 执行从视频帧到位图对象的转换操作
        options.transform(new BitmapTransformation() {
            @Override
            protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                return toTransform;
            }

            @Override
            public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
                messageDigest.update(getPackageName().getBytes(StandardCharsets.UTF_8));
            }
        });
        return options;
    }


    private int mBlock = 50 * 1024;

    /**
     * 分段传输图片
     */
    private void sendImage() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 把位图数据压缩为字节数组输出流
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img);
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos);
        byte[] bytes = baos.toByteArray();
        int count = bytes.length / mBlock + 1;
        // 下面把图片数据经过 BASE64 编码后发给 Socket 服务器
        for (int i = 0; i < count; i++) {
            String encodeData = "";
            if (i == count - 1) {
                int remain = bytes.length % mBlock;
                byte[] temp = new byte[remain];
                System.arraycopy(bytes, i * mBlock, temp, 0, remain);
                encodeData = Base64.encodeToString(temp, Base64.DEFAULT);
            } else {
                byte[] temp = new byte[mBlock];
                System.arraycopy(bytes, i * mBlock, temp, 0, mBlock);
                encodeData = Base64.encodeToString(temp, Base64.DEFAULT);
            }
            // 往 Socket 服务器发送本段的图片数据
            ImagePart part = new ImagePart("img", encodeData, i, bytes.length);
//            SocketUtil.emit(mSocket, "send_image", part);
        }
    }


    private String mLastFile;   // 上次的文件名
    private int mReceiveCount;  // 接收包的数量
    private byte[] mReceiveData;    // 收到的字节数组
    /**
     * 接收对方传来的图片数据
     * @param args
     */
    private void receiveImage(Object... args) {
        JSONObject json = (JSONObject) args[0];
        ImagePart part = new Gson().fromJson(json.toString(), ImagePart.class);
        if (!part.getName().equals(mLastFile)) {
            // 文件名不同，表示开始接收新文件
            mLastFile = part.getName();
            mReceiveCount = 0;
            mReceiveData = new byte[part.getLength()];
        }
        mReceiveCount++;
        // 把接收到的图片数据通过 BASE64 解码为字节数组
        byte[] temp = Base64.decode(part.getData(), Base64.DEFAULT);
        System.arraycopy(temp, 0, mReceiveData, part.getSeq() * mBlock, temp.length);
        // 所有数据包都接收完毕
        if (mReceiveCount >= part.getLength() / mBlock + 1) {
            // 从字节数组中解码得到位图对象
            Bitmap bitmap = BitmapFactory.decodeByteArray(mReceiveData, 0, mReceiveData.length);
        }
    }
}